
import os from '../os.js';

/**
 * 获取默认日志数据
 */
const getLogsData = function(logType = 'app', markType = 1) 
{
  let logsData = {
    log_type: '',
    app_id: 0,
    oa_click_id: '',
    oa_media_id: 0,
    oa_prefix_mark: '',
    oa_mark: '',
    oa_aid: '',
    oa_campaign_id: '',
    oa_cid: '',
    oa_mid: '',
    oa_team_members: 0,
    oa_team_leader: 0,
    iaa_slot_id: 0,
    iaa_ad_id: 0,
    iaa_strategy_id: 0,
    iaa_code_id: '',
    uid: 0,
    deviceid: '',
    brand: '',
    model: '',
    os: '',
    device_imei: '',
    device_oaid: '',
    device_androidid: '',
    device_idfa: '',
    order_id: '',
    currency_amount: 0,
    pay_product_id: '',
    pay_type: '',
    payment_id: 0,
    session_id: '',
    appPath: '',
    appTo: '',
    appFrom: '',
    method_id: 0,
    method_cid: 0,
    method_rid: 0,
    method_amount: 0,
    method_mark: '',
    method_mark_1: '',
    app_ureg_time: '',
    app_first_upay_time: '',
    Ipv6: '',
    Ipv4: '',
    ip_number: 0,
    geo: '',
    behavior_time: '',
    log_time: '',
    log_desc: ''
  }

  // 应用日志
  if(logType === 'app'){
    switch (markType) {
      case 1:
        logsData.log_type = 'appInit';
        logsData.log_desc = '应用启动日志';
        break;
      case 2:
        logsData.log_type = 'appLogin';
        logsData.log_desc = '应用登录日志';
        break;
      case 3:
        logsData.log_type = 'appPageShow';
        logsData.log_desc = '应用页面展示日志';
        break;
      case 4:
        logsData.log_type = 'appPageClick';
        logsData.log_desc = '应用按钮点击日志';
        break;
      case 5:
        logsData.log_type = 'appPageScroll';
        logsData.log_desc = '应用页面滑动日志';
        break;
      case 6:
        logsData.log_type = 'appExit'; 
        logsData.log_desc = '应用退出';
        break;
      default:
        break;
    }
  }

  // 短剧日志
  if(logType === 'video'){
    switch (markType) {
      case 1:
        logsData.log_type = 'videoStart';
        logsData.log_desc = '视频开始播放';
        break;
      case 2:
        logsData.log_type = 'videoDone';
        logsData.log_desc = '视频完成播放';
        break;
      case 3:
        logsData.log_type = 'videoPlayLog';
        logsData.log_desc = '视频播放日志';
        break;
      case 4:
        logsData.log_type = 'videoPause';
        logsData.log_desc = '视频暂停播放';
        break;
      case 5:
        logsData.log_type = 'videoPlay';
        logsData.log_desc = '视频继续播放';
        break;
      case 6:
        logsData.log_type = 'videoCollect'; 
        logsData.log_desc = '视频收藏';
        break;
      case 7:
        logsData.log_type = 'videoCancelCollect'; 
        logsData.log_desc = '视频取消收藏';
        break;
      case 8:
        logsData.log_type = 'videoLike'; 
        logsData.log_desc = '视频点赞';
        break;
      case 9:
        logsData.log_type = 'videoCancelLike'; 
        logsData.log_desc = '视频取消点赞';
        break;
      case 10:
        logsData.log_type = 'videoProgressSlide';
        logsData.log_desc = '视频进度条条滑动';
        break;
      case 11:
        logsData.log_type = 'videoNext';
        logsData.log_desc = '视频下一集';
        break;
      case 12:
        logsData.log_type = 'videoJump';
        logsData.log_desc = '视频跳集';
        break;
      case 13:
        logsData.log_type = 'videoExit';
        logsData.log_desc = '离开视频';
        break;
      case 14:
        logsData.log_type = 'videoUnlock';
        logsData.log_desc = '视频解锁';
        break;
      case 15:
        logsData.log_type = 'videoChangeSpeed';
        logsData.log_desc = '视频切换倍速';
        break;
      case 16:
        logsData.log_type = 'videoError';
        logsData.log_desc = '播放器错误信息';
        break;
      default:
        break;
    }
  }

  // IAA日志
  if(logType === 'iaa'){
    switch (markType) {
      case 1:
        logsData.log_type = 'iaaReq';
        logsData.log_desc = '商业化广告加载';
        break;
      case 2:
        logsData.log_type = 'iaaReqDone';
        logsData.log_desc = '商业化广告加载成功';
        break;
      case 3:
        logsData.log_type = 'iaaReqFail';
        logsData.log_desc = '商业化广告加载失败';
        break;
      case 4:
        logsData.log_type = 'iaaShow';
        logsData.log_desc = '商业化广告展示';
        break;
      case 5:
        logsData.log_type = 'iaaClick';
        logsData.log_desc = '商业化广告点击';
        break;
      case 6:
        logsData.log_type = 'iaaClose'; 
        logsData.log_desc = '商业化广告关闭';
        break;
      default:
        break;
    }
  }

  // 支付日志
  if(logType === 'pay'){
    switch (markType) {
      case 1:
        logsData.log_type = 'payPage';
        logsData.log_desc = '支付页面/弹窗打开';
        break;
      case 2:
        logsData.log_type = 'payPageScroll';
        logsData.log_desc = '支付页面/弹窗内滚动';
        break;
      case 3:
        logsData.log_type = 'payPageExit';
        logsData.log_desc = '支付页面/弹窗离开或隐藏';
        break;
      case 4:
        logsData.log_type = 'payOrder';
        logsData.log_desc = '下单';
        break;
      case 5:
        logsData.log_type = 'payDone'; 
        logsData.log_desc = '支付完成';
        break;
      case 6:
        logsData.log_type = 'payError'; 
        logsData.log_desc = '支付错误信息';
        break;
      default:
        break;
    }
  }

  // 广告日志
  if(logType === 'ad'){
    switch (markType) {
      case 1:
        logsData.log_type = 'advertShow';
        logsData.log_desc = '广告展示日志';
        break;
      case 2:
        logsData.log_type = 'advertClick';
        logsData.log_desc = '广告点击日志';
        break;
      case 3:
        logsData.log_type = 'advertCallBack';
        logsData.log_desc = '广告回传日志';
        break;
      default:
        break;
    }
  }

  return logsData;
}

/**
 * opt  object | string
 * to_url object | string
 * 例:
 * this.Tips('/pages/test/test'); 跳转不提示
 * this.Tips({title:'提示'},'/pages/test/test'); 提示并跳转
 * this.Tips({title:'提示'},{tab:1,url:'/pages/index/index'}); 提示并跳转值 tabBar 页面
 * icon:success=成功，fail=失败，loading=加载中，none=不显示图标
 * tab=1 跳转到 tabBar 页面，并关闭其他所有非 tabBar 页面
 * tab=2 保留当前页面，跳转到应用内的某个页面，但是不能跳转到 tabBar 页面
 * tab=3 一定时间后返回上页面
 * tab=4 关闭所有页面，打开应用内的某个页面
 * tab=5 关闭当前页面，跳转到应用内的某个页面，不能跳转到 tabBar 页面
 */
const Tips = function (opt, to_url) 
{
  if (typeof opt == 'string') {
    to_url = opt;
    opt = {};
  }
  var title = opt.title || '', icon = opt.icon || 'none', endtime = opt.endtime || 1500;
  if (title) os.showToast({ title: title, icon: icon, duration: endtime })
  if (to_url != undefined) {
    if (typeof to_url == 'object') {
      var tab = to_url.tab || 1, url = to_url.url || '';
      switch (tab) {
        case 1:
          setTimeout(function () {
            os.switchTab({
              url: url
            })
          }, endtime);
          break;
        case 2:
          setTimeout(function () {
            os.navigateTo({
              url: url,
            })
          }, endtime);
          break;
        case 3:
          setTimeout(function () {
            os.navigateBack({
              delta: parseInt(url),
            })
          }, endtime);
          break;
        case 4:
          setTimeout(function () {
            os.reLaunch({
              url: url,
            })
          }, endtime);
          break;
        case 5:
          setTimeout(function () {
            os.redirectTo({
              url: url,
            })
          }, endtime);
          break;
      }

    }else if(typeof to_url == 'function'){
      setTimeout(function () { 
        to_url && to_url();
      }, endtime);
    }else{
      //没有提示时跳转不延迟
      setTimeout(function () {
        os.navigateTo({
          url: to_url,
        })
      }, title ? endtime : 0);
    }
  }
}

/**
 * 延迟
 * @param int timeout 时间
 */
const sleep = (timeout = 500) => {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve('1');
    }, timeout);
  });
}

/**
 * 今天开始时间戳
 */
const getTsTimestamp = () => {
  let todayStart = new Date();
  todayStart.setHours(0, 0, 0, 0);
  return todayStart.getTime()/1000;
}

/**
 * 昨天开始时间戳
 */
const getYsTimestamp = () => {
  const now = new Date();
  const yesterday = new Date(now.getTime() - (24 * 60 * 60 * 1000)); 
  return Math.floor(yesterday.setHours(0, 0, 0, 0))/1000;
}

/**
 * 当前时间戳
 */
const getTimestamp = () => {
  return Math.floor(Date.now() / 1000);
}

const getCurrentTime = () => {
  const now = new Date();
  const year = now.getFullYear();
  const month = (now.getMonth() + 1).toString().padStart(2, '0');
  const day = now.getDate().toString().padStart(2, '0');
  const hours = now.getHours().toString().padStart(2, '0');
  const minutes = now.getMinutes().toString().padStart(2, '0');
  const seconds = now.getSeconds().toString().padStart(2, '0');
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}

const isOver24Hours = (time) => {
  const createTime = new Date(time);
  const now = new Date();
  const diff = now - createTime;
  return diff > 24 * 60 * 60 * 1000;
}

/*
* 合并数组
*/
const SplitArray = function (list, sp) 
{
  if (typeof list != 'object') return [];
  if (sp === undefined) sp = [];
  for (var i = 0; i < list.length; i++) {
    sp.push(list[i]);
  }
  return sp;
}

/**
 * 移除数组中的某个数组并组成新的数组返回
 * @param array array 需要移除的数组
 * @param int index 需要移除的数组的键值
 * @param string | int 值
 * @return array
 * 
*/
const ArrayRemove = (array,index,value) => {
  const valueArray=[];
  if (array instanceof Array){
    for (let i = 0; i < array.length;i++){
      if (typeof index == 'number' && array[index] != i){
        valueArray.push(array[i]);
      } else if (typeof index == 'string' && array[i][index] != value){
        valueArray.push(array[i]);
      }
    }
  }
  return valueArray;
}

/**
 * 检查空数组对象
 */
const isNullOrEmpty = (value) => {
  return value === null || (typeof value === 'object' && Object.keys(value).length === 0) || value === undefined || value === '' || value.length === 0;
}

const isURL = (url) => {
  return /^https?:\/\//i.test(url);
}

/**
   * 数组-观看一次解锁集
   */
const unlockEpisode = (array, id, n = 0) => {
  const idx = array.findIndex(item => item.chapter_id === id);
  let ids = [];
  if (idx !== -1) {
    array[idx].isUnlock = true;
    array[idx].is_unlock = 0;
    ids.push(id);
    array.forEach((item, index) => {
      if (index > idx && n > 0 && item.is_unlock === 1) {
        array[index].isUnlock = true;
        array[index].is_unlock = 0;
        n--;
        ids.push(item.chapter_id);
      }
    });
  }
  return ids;
}

const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return `${[year, month, day].map(formatNumber).join('/')} ${[hour, minute, second].map(formatNumber).join(':')}`
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : `0${n}`
}

module.exports = {
  getLogsData,
  Tips,
  sleep,
  SplitArray,
  ArrayRemove,
  getTsTimestamp,
  getYsTimestamp,
  getTimestamp,
  isOver24Hours,
  isNullOrEmpty,
  unlockEpisode,
  isURL,
  getCurrentTime,
  formatTime
}
